package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.product.service.RedisTestService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RedisTestServiceImpl implements RedisTestService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * redis的所测试demo1
     */
    @Override
    public synchronized void lockDemo1() {
//        //从缓存中获取key
//        String s = stringRedisTemplate.boundValueOps("demo1_num").get();
//        //判断是否为空
//        if (StringUtils.isEmpty(s)){
//            return;
//        }
//        //若不为空
//        Integer num = Integer.parseInt(s);
//        //自增保存
//        stringRedisTemplate.boundValueOps("demo1_num").set(++num + "");
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,3, TimeUnit.SECONDS);
        //lock为true的时候代表获取到了锁
        if (lock){
            //从缓存中获取key
            String s = stringRedisTemplate.boundValueOps("demo1_num").get();
            //判断是否为空
            if (StringUtils.isEmpty(s)){
                return;
            }
            //若不为空
            Integer num = Integer.parseInt(s);
            //自增保存
            stringRedisTemplate.boundValueOps("demo1_num").set(++num + "");
//            //判断是否为本身的锁
//            if (uuid.equals(stringRedisTemplate.opsForValue().get("lock"))){
//                //释放锁
//                stringRedisTemplate.delete("lock");
//            }
            DefaultRedisScript<Long> script = new DefaultRedisScript<>();

            //设置lua脚本
            script.setScriptText("if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end");
            //设置返回类型
            script.setResultType(Long.class);
            //执行脚本释放锁
            stringRedisTemplate.execute(script, Arrays.asList("lock"),uuid);
        }else {
            try {
                //没有获取到锁,线程睡觉1秒
                Thread.sleep(100);
                //重试：递归
                lockDemo1();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Autowired
    private RedissonClient redissonClient;
    @Override
    public void lockDemo2() {
        //获取锁
        RLock lock = redissonClient.getLock("lock");
        //尝试加锁
        try {
            if (lock.tryLock(100,2,TimeUnit.SECONDS)){
                //从缓存中获取key
                String s = stringRedisTemplate.boundValueOps("demo1_num").get();
                //判断是否为空
                if (StringUtils.isEmpty(s)){
                    return;
                }
                //若不为空
                Integer num = Integer.parseInt(s);
                //自增保存
                stringRedisTemplate.boundValueOps("demo1_num").set(++num + "");
            }
            else {
                    //没有获取到锁,线程睡觉1秒
                    Thread.sleep(100);
                    //重试：递归
                    lockDemo2();
                }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}
